﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.Preferences;
using ApplicationLibrary.SqlConnector;
using Plumber.Accounting.Library;
using Plumber.Accounting.ModuleData;
using Plumber.Accounting.Preferences;
using Plumber.Accounting.Reports.DataSet;
using Plumber.Accounting.Reports;

namespace Plumber.Accounting.Forms
{
    public partial class LiquidationTax : ApplicationLibrary.DBManager.DocumentForm
    {
        private const string PRINT_SUMMARY = "PRINT_SUMMARY";
        private EnumsManager<PeriodType> eMonthName        = null;
        private AccountingPref accountingPref             = null;
        private RRJournalEntryDetail rrJournalEntryDetail = null;
        private DRJournalEntry dRJournalEntry             = null;
        private EnumsManager<TaxRegisterStatus> ePurchase = null;
        private EnumsManager<TaxRegisterStatus> eSale     = null;

        public double totdebit { get; set; }

        public LiquidationTax()
            : base(Properties.Resources.FN_LiquidationTax)
        {
            InitializeComponent();
            keyControl = null;

            totdebit = 100;
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarLiquidationTaxParam(int.Parse(cbbYear.Text), eMonthName.GetValue().Int());
        }

        protected override void OnAttachData()
        {
            accountingPref = new PreferencesManager<AccountingPref>(formName, null).ReadPreference();

            for (int t = 2011; t <= GlobalInfo.CurrentDate.Year; t++)
                cbbYear.Items.Add(t);

            dbManager = new dbmanagerLiquidationTax("LiquidationTaxForm", new RadarLiquidationTax(), this);
            dbManager.AddMaster(this, PL_LiquidationTax.Name, true);

            eMonthName = new EnumsManager<PeriodType>(cbbMonth);
            fncJournalNo.AttachCounterType(GlobalInfo.GetCounter(Properties.Resources.CN_JournalEntry), GlobalInfo.CurrentDate, null);


            eSale = new EnumsManager<TaxRegisterStatus>(cbbSaleStatus);
            ePurchase = new EnumsManager<TaxRegisterStatus>(cbbPurchaseStatus);

            rrJournalEntryDetail = new RRJournalEntryDetail();
            dRJournalEntry = new DRJournalEntry(false);
        }

        protected override void OnBindData()
        {
            BindControl(cbbMonth, PL_LiquidationTax.Month, "SelectedValue", NullValue.NotSet);
            BindControl(cbbYear, PL_LiquidationTax.Year, "Text", NullValue.NotSet);
            BindControl(ntbSaleDebit, PL_LiquidationTax.SaleDebit);
            BindControl(ntbSaleCredit, PL_LiquidationTax.SaleCredit);
            BindControl(ntbPurchaseDebit, PL_LiquidationTax.PurchaseDebit);
            BindControl(ntbPurchaseCredit, PL_LiquidationTax.PurchaseCredit);
            BindControl(ntbPreviousCredit, PL_LiquidationTax.PrevoiusCredit);
            BindControl(ntbCurrentCredit, PL_LiquidationTax.CurrentCredit);
            BindControl(fncJournalNo, PL_LiquidationTax.JournalEntryNo);
            BindControl(cbbSaleStatus, PL_LiquidationTax.SaleRegister, "SelectedValue");
            BindControl(cbbPurchaseStatus, PL_LiquidationTax.PurchaseRegister, "SelectedValue");
            BindControl(ntbTotDebit);
            BindControl(ntbTotCredit);
            BindControl(ntbTotToPay);
            BindControl(ntbTotPayed);
            BindControl(btnCreatePayment);
            BindControl(ctbPaymentDate);
        }

        protected override bool OnEnableToolbarButtons(ToolStripButton button)
        {
            if (button.Name == "tbnNew")
                return false;

            return base.OnEnableToolbarButtons(button);
        }

        protected override void OnDisableControlsForEdit()
        {
            cbbMonth.Enabled          = false;
            cbbYear.Enabled           = false;
            ntbSaleDebit.Enabled      = false;
            ntbSaleCredit.Enabled     = false;
            ntbPurchaseDebit.Enabled  = false;
            ntbPurchaseCredit.Enabled = false;
            ntbPreviousCredit.Enabled = false;
            fncJournalNo.Enabled      = false;
            ctbPaymentDate.Enabled    = false;
            ntbTotDebit.Enabled       = false;
            ntbTotCredit.Enabled      = false;
            ntbTotToPay.Enabled       = false;
            ntbCurrentCredit.Enabled  = false;
            cbbPurchaseStatus.Enabled = false;
            cbbSaleStatus.Enabled     = false;

            btnCreatePayment.Enabled = ePurchase.GetValue() == TaxRegisterStatus.E_Final && 
                                        eSale.GetValue() == TaxRegisterStatus.E_Final && 
                                        ntbTotToPay.Double > 0;
        }

        protected override void OnPrepareAuxData()
        {
            ntbTotCredit.Double = ntbSaleCredit.Double + ntbPurchaseCredit.Double + ntbPreviousCredit.Double;
            ntbTotDebit.Double = ntbSaleDebit.Double + ntbPurchaseDebit.Double;

            ntbTotToPay.Double = ntbTotDebit.Double > ntbTotCredit.Double
                                    ? ntbTotDebit.Double - ntbTotCredit.Double
                                    : 0;

            if (!string.IsNullOrEmpty(fncJournalNo.Text))
            {
                if (dRJournalEntry.Find(fncJournalNo.Text))
                {
                    ctbPaymentDate.Today = dRJournalEntry.GetValue<DateTime>(PL_JournalEntry.PostingDate);
                    if (rrJournalEntryDetail.Find(fncJournalNo.Text))
                        ntbTotPayed.Double = rrJournalEntryDetail.GetValue<double>(PL_JETemplateDetail.From);
                }
            }
            base.OnPrepareAuxData();
        }

        protected override bool OnBeforeDelete()
        {
            if (!base.OnBeforeDelete())
                return false;

            return true;
        }

        protected override void OnAddSplitMenuButton()
        {
            AddSplitPreviewButton(Properties.Resources.PRNT_SUMMARY, PRINT_SUMMARY, PrintType.Letter, Properties.Resources.B_Invoice);
            AddSplitPrintButton(Properties.Resources.PRNT_SUMMARY, PRINT_SUMMARY, PrintType.Letter, Properties.Resources.B_Invoice);
        }

        protected override bool OnPrintDocument(PrintInfo sender, printerForm pf)
        {
            switch (sender.ReportName)
            {
                case PRINT_SUMMARY:
                    return PrintSummary(pf);
                default:
                    return true;
            }
        }

        #endregion Virtual Method

        private bool PrintSummary(printerForm pf)
        {
            DSLiquidationTax dsLiquidationTax = new DSLiquidationTax();
            DSLiquidationTax.LiquidationTaxRow row = dsLiquidationTax.LiquidationTax.NewLiquidationTaxRow();

            row[PL_LiquidationTax.Month.Name]            = cbbMonth.Text;
            row[PL_LiquidationTax.Year.Name]             = cbbYear.Text;
            row[PL_LiquidationTax.SaleDebit.Name]        = ntbSaleDebit.Double;
            row[PL_LiquidationTax.SaleCredit.Name]       = ntbSaleCredit.Double;
            row[PL_LiquidationTax.PurchaseCredit.Name]   = ntbPurchaseCredit.Double;
            row[PL_LiquidationTax.PurchaseDebit.Name]    = ntbPurchaseDebit.Double;
            row[PL_LiquidationTax.PrevoiusCredit.Name]   = ntbPreviousCredit.Double;
            row[PL_LiquidationTax.CurrentCredit.Name]    = ntbCurrentCredit.Double;
            row["TotalCredit"]                           = ntbTotCredit.Double;
            row["TotalDebit"]                            = ntbTotDebit.Double;
            row["TotalToPay"]                            = ntbTotToPay.Double;
            row[PL_LiquidationTax.SaleRegister.Name]     = cbbSaleStatus.Text;
            row[PL_LiquidationTax.PurchaseRegister.Name] = cbbPurchaseStatus.Text;

            dsLiquidationTax.LiquidationTax.Rows.Add(row);

            pf.ShowReport(new RPTLiquidationTax(), dsLiquidationTax);

            return true;
        }

        private void btnCreatePayment_Click(object sender, EventArgs e)
        {
            CreateLiquidationTaxPayment cp = new CreateLiquidationTaxPayment();
            string jeNumber = fncJournalNo.Text;

            cp.AmountTotal = ntbTotToPay.Double;
            cp.AmountToPayed = ntbTotToPay.Double;
            cp.JEDate = GlobalInfo.CurrentDate;

            OpenNewForm(cp, true);

            if (cp.DialogResult == System.Windows.Forms.DialogResult.OK &&
                    CreatePayment(cp.AmountToPayed, cp.BankCash, cp.BankCashCode, cp.JEDate, ref jeNumber))
            {
                MyMessageBox(Properties.Resources.Msg_PaymentOK, Properties.Resources.Msg_Payment, MessageBoxButtons.OK, MessageBoxIcon.Information);
                fncJournalNo.Text = jeNumber;
                ToolbarEvent(ToolbarEventKind.Save);
            }
        }

        private bool CreatePayment(double payed, string bankcash, string code, DateTime date, ref string jeNumber)
        {
            using (JournalEntriesCreator jC = new JournalEntriesCreator())
            {
                bool ok = false;
                if (!string.IsNullOrEmpty(jeNumber) && jC.Find(jeNumber))
                    ok = jC.Edit();
                else
                    ok = jC.AddNew();
                if (!ok)
                    return false;

                string desc = string.Format(Properties.Resources.Msg_PayedLiquidationTax, cbbMonth.Text, cbbYear.Text);
                jC.SetHeader(date, desc);

                if (jC.RowCount > 0)
                    jC.GetDataGrid.Clear();

                jC.AddRow(bankcash, code, desc, "", payed, 0);
                jC.AddRow(accountingPref.TypeTreasuryTax, accountingPref.MasterTreasuryTax, desc, "", 0, payed);

                jeNumber = string.Empty;
                if (jC.Save())
                {
                    jeNumber = jC.JeNumber;
                    return true;
                }
                return false; ;
            }
        }

        private bool LiquidationTax_OnEnableToolbarSplitButtons(ToolStripSplitButton sender)
        {
            return true;
        }
    }

    #region DbManager dbmanagerLiquidationTax

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerLiquidationTax : DBManager
    {
        public dbmanagerLiquidationTax(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        { }

        protected override string CreateMasterQuery()
        {
            this.Table = new PL_LiquidationTax();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(this.Table);
            qB.AddCompare(PL_LiquidationTax.Year, "@p1");
            qB.AddCompare(PL_LiquidationTax.Month, "@p2");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter p1 = new SqlABParameter("@p1", PL_LiquidationTax.Year);
            p1.Value = PL_LiquidationTax.Year.DefaultValue;
            PList.Add(p1);
            SqlABParameter p2 = new SqlABParameter("@p2", PL_LiquidationTax.Month);
            p2.Value = PL_LiquidationTax.Month.DefaultValue;
            PList.Add(p2);
            return PList;
        }

        protected override void SetParameters(IRadarParameters key, DBCollection collection)
        {
            collection.Parameter[0].Value = key[0];
            collection.Parameter[1].Value = key[1];
        }
    }

    #endregion DbManager dbmanagerLiquidationTax
}